<script setup lang="ts">
import { ref, h } from "vue";
import {
  DownloadBySettlementAgent,
  getListDtl,
  getListByAgent
} from "@/api/statement";

import {
  getAgentAccountTotalAgent,
  getFlowAgentFlowType,
  getFlowAgentListAgent,
  getWithdrawalOrderAgentInfo
} from "@/api/commission";
import { downloadFile,formatDateTime } from "@/utils";
import { ElTooltip } from "element-plus";
defineOptions({
  name: "Account"
});

const size = ref("default");
const background = ref(false);
const disabled = ref(false);
const dialogTableVisible = ref(false);
const gridData = ref([]);

const totalData = ref({}); // 佣金账户金额
let tableData = ref([]);//列表数据来源
const pickerValue = ref("");//时间
const flowTypeOptions = ref([]);
const flowTypeValue = ref('');
const pageTotal = ref(0);
const currentPage = ref(1);
const drawer = ref(false);
const drawerInfo = ref({})

//获取佣金账户
function getTotalAmount() {
      getAgentAccountTotalAgent().then(
          (res: any) => {
            totalData.value = res?.data;
            console.log(totalData.value, res, 'getAgentAccountTotalAgent')
          }
      )
}
getTotalAmount();

//获取流水类型数据
    getFlowAgentFlowType().then((res:any) =>{
    flowTypeOptions.value = res.data;
})

//查询列表
function queryListTableData(params?) {
      const [start, end] = getPickerTime()
      const [deptId] = flowTypeOptions.value
      const _params = {
            pageNum: 1,
            pageSize: 10,
            createTimeStart: start,
            createTimeEnd: end,
            total: 0,
            ...params
        };
      if (deptId && deptId.deptId) {
            _params.deptId = deptId.deptId
      }
      if(flowTypeValue){
        _params.flowType = flowTypeValue.value
      }
      getFlowAgentListAgent({ ..._params }).then((res: any) => {
            tableData.value = res.rows;
            pageTotal.value = res.total;
      });
}
queryListTableData();

    // 选择时间时间picker变化的时候
const pickerChange = () => {
      queryListTableData({
            total: 6
        })
}

// 重置页面
const onReset = () => {
    pickerValue.value = ''
    flowTypeValue.value = ''
    pageTotal.value = 0
    currentPage.value = 1
    queryListTableData();
}



//选择时间
function getPickerTime() {
    const [startTime, endTime] = pickerValue.value
    const start = new Date(startTime)
    const end = new Date(endTime)
    return startTime ? [formatDateTime(start), formatDateTime(end)] : ''
}
getPickerTime();

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  queryListTableData(val);
};

const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  queryListTableData(val);
};

const downloadBill = id => {
  console.log(id);
  DownloadBySettlementAgent({ id }, { responseType: "blob" }).then(
    (res: any) => {
      const { data, headers } = res;
      downloadFile(data, headers);
    }
  );
};
let getInfoID: string | number = "";
const getInfo = (
  id: string | number,
  pageNum: number = 1,
  pageSize: number = 10
) => {
  getInfoID = id;
  getListDtl({ id, pageNum, pageSize, total: 0 }).then((res: any) => {
    const { data, rows } = res;
    if (rows.length) {
      const one = rows[0];
      dialogTitle.value = `${one.startDate}~${one.endDate}对账单`;
    }
    gridData.value = rows;
    dialogTotal.value = data.total;
    console.log(res);
  });
};
const dialogTitle = ref("");
const dialogTotal = ref(0);
const dialogCurrent = ref(1);
const showOneTable = ref(true);
const dialogHandleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  getInfo(val);
};

const dialogHandleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  getInfo(val);
};

const closeDialog = () => {
  showOneTable.value = true;
};
const handleDialogDetails = (data) =>{
  getListByAgent(data.id).then((res: any) => {      
        drawerInfo.value = res.data
        drawer.value = true
        console.log( drawerInfo.value,'详情')
});
};
const renderstate = ({ column }) => {
  // return h(ElTooltip, {content: 'dfddfdfd',placement: 'top-start', effect: 'light'}, [column.label])
  return h("span", column.label);
};
</script>
<template>
  <div class="account">
    <el-card class="box-card">
      <div class="top">
        <div class="">
          <div class="total">
            <div class="label">可提现金额 </div>
            <el-tooltip placement="top" content="对账单已确认，但还未到提现时间，默认每周五上午10点自动提现。">
              <el-icon color="#999">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
          </div>
          <div class="totalNum font-number-medium">
            <span>¥{{ totalData.actualAmount }}</span>
          </div>
        </div>
        <div class="item-wrapper">
            <div class="item">
              <div class="label">账户总金额</div>
              <div class="value font-number-bold">                
                  <span>¥{{ totalData.totalAmount }}</span>                
              </div>
            </div>
            <el-icon color="#8c8c8c">
              <SemiSelect />
            </el-icon>
            <div class="item">
              <div class="label">
                未入账金额
                <el-tooltip placement="top" content="您已赚取的推广金额，但系统尚未生成对账单，默认每周三会为您生成。">
                  <el-icon color="#8c8c8c">
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
              </div>
              <div class="value font-number-medium">
                  <span>¥{{ totalData.frozenAmount }}</span>
              </div>
            </div>
            <el-icon color="#8c8c8c">
              <SemiSelect />
            </el-icon>
            <div class="item">
              <div class="label">待对账金额
                <el-tooltip placement="top" content="已生成对账单，但还未进行确认。">
                  <el-icon color="#8c8c8c">
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
              </div>
              <div class="value font-number-medium">
                  <span>
                    ¥{{ totalData.cumulativeWithdrawAmount }}</span>
              </div>
            </div>
            <el-icon color="#8c8c8c">
              <SemiSelect />
            </el-icon>
            <div class="item">
              <div class="label">提现中金额
                <el-tooltip placement="top" content="已生成对账单，但还未进行确认。">
                  <el-icon color="#8c8c8c">
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
              </div>
              <div class="value font-number-medium">
                  <span>¥{{ totalData.withdrawAmount }}</span>
              </div>
            </div>
        </div>
      </div>
    </el-card>
    <div class="main">
      <div class="search">
        <div class="select">
          <el-select v-model="flowTypeValue" size="large" placeholder="请选择流水类型">
            <el-option v-for="item in flowTypeOptions" :key="item.code" :label="item.desc" :value="item.code" />
          </el-select>
        </div>
        <div class="block dl">
          <el-date-picker @change="pickerChange" v-model="pickerValue" size="large" type="daterange"
                    range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间">
          </el-date-picker>
        </div>
        <div class="search-btn">
          <el-button size="large" type="primary" @click="queryListTableData">查询</el-button>
          <el-button  size="large" @click="onReset">重置</el-button>
        </div>
      </div>
      <div class="c-page__bg">
        <el-table :data="tableData">          
          <el-table-column prop="createTime" label="交易时间"  />
          <el-table-column prop="flowTypeDisplay" label="交易类型" :render-header="renderstate"/>
          <el-table-column width="180" prop="tranRemark" label="交易描述" />
          <el-table-column prop="amountOfPayment" label="交易金额（元）" />
          <el-table-column prop="actualAmount" label="可用余额（元）" />          
          <el-table-column #default="{ row }" label="操作">           
            <span class="c-text-primary" @click="handleDialogDetails(row.id)">详情</span>
          </el-table-column>
        </el-table>
        <div class="pagination-block">
          <el-pagination v-model:current-page="currentPage" :page-size="10" :size="size" :disabled="disabled"
            :background="background" layout="total, prev, pager, next" :total="pageTotal"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>

      <!-- 详情-->
      <el-drawer v-model="drawer" title="详情" size="40%">
                <el-form class="c-drawer-form">
                  <div class="c-info__title">基本信息</div>
                    <el-form-item label="提现单号">{{ drawerInfo.amountOfApply }}</el-form-item>
                    <el-form-item label="提现方式">{{ drawerInfo.amountOfPre }}</el-form-item>
                    <el-form-item label="提现金额">{{ drawerInfo.invoiceBatchTotalDisplay }}</el-form-item>
                    <el-form-item label="提现时间">{{ drawerInfo.invoiceBatchTotalDisplay }}</el-form-item>
                    <el-form-item label="提现状态">{{ drawerInfo.invoiceBatchTotalDisplay }}</el-form-item>
                    <el-form-item label="提现说明">{{ drawerInfo.invoiceBatchTotalDisplay }}</el-form-item>
                    <el-form-item label="打款凭证">{{ drawerInfo.invoiceBatchTotalDisplay }}</el-form-item>

                    <div class="c-info__title">关联信息</div>
                    <el-form-item label="对账单">
                      <span class="c-text-primary" @click="downloadBill(drawerInfo.id)"
                            >下载账单</span
                          >
                          <span
                            class="c-text-primary"
                            @click="getInfo(drawerInfo.id), (dialogTableVisible = true)"
                            >查看</span
                          >
                    </el-form-item>                                      
                </el-form>
            </el-drawer>
      <!-- <el-dialog v-model="dialogTableVisible" :title="dialogTitle" width="1200" center> -->
      <el-dialog v-model="dialogTableVisible" width="1200" @close="closeDialog">
        <div class="system-icon-content">
          <template v-if="showOneTable">
            <div class="flex-row">{{ dialogTitle }}</div>
            <el-table :data="gridData">
              <el-table-column label="序号" type="index" />
              <el-table-column property="merchantsInfoIdDisplay" :show-overflow-tooltip="true" label="商户名称" />
              <el-table-column property="deptIdDisplay" label="走款服务商" />
              <el-table-column property="totalAmount" label="总金额" />
              <el-table-column property="incomeRate" label="服务费率" />
              <el-table-column property="costRate" label="结算费率" />
              <el-table-column property="commissionDeductionProportion" label="推广点" />
              <el-table-column property="settlementAmount" label="结算金额" />
              <!-- <el-table-column #default="{ row }" label="操作">
                <span class="c-text-primary" @click="handleDialogDetails(row), (showOneTable = false)">查看明细</span>
              </el-table-column> -->
            </el-table>
            <div class="pagination-block">
              <el-pagination v-model:current-page="dialogCurrent" :page-size="10" :size="size" :disabled="disabled"
                :background="background" layout="total, prev, pager, next" :total="dialogTotal"
                @size-change="dialogHandleSizeChange" @current-change="dialogHandleCurrentChange" />
            </div>
          </template>
          <template v-else>
            <div class="back">
              <div class="back-text" @click="showOneTable = true">
                <el-icon>
                  <ArrowLeftBold />
                </el-icon>
                <span>返回</span>
              </div>
              <span class="title">{{ dialogTitle }}</span>
            </div>
            <el-table :data="[]">
              <el-table-column label="操作" />
            </el-table>
          </template>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.account {
  height: 100%;
  overflow: hidden;
  padding: 10px;

  .top {
    width: 580px;
    .total{display: flex;}
    .label{
      margin-right:5px;
    }
  }
}
.font-number-medium{
  font-family: Barlow-m;
}
.main {
  height: 100%;
  overflow: hidden;
  // padding: 10px;
  // background-color: #fff;
  border-radius: 5px;
  margin-top:20px;
}

.wrapper {
  background-color: #fff;
  border-radius: 10px;

  .account-wrapper {
    padding: 2.222vh 1.25vw;
  }

  .title {
    font-size: 16px;
    font-weight: 700;
    color: #262626;
  }
}

.account-wrapper {
  background-color: #fff;
  border-radius: 10px;
  padding: 2.222vh 1.25vw;
}

.totalNum {
  margin-top: 8px;
  font-size: 24px;
  line-height: 40px;
  font-weight: 600;
  color: #1c9fff;
}

.item-wrapper {
  margin-top: 2.222vh;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .item {
    padding: 1.4814814815vh 1.25vw 1.4814814815vh 1.25vw;

    .label {
      font-size: 14px;
      color: #8c8c8c;
      display: flex;
      align-items: center;
    }

    .value {
      margin-top: 8px;
      font-size: 18px;
      color: #262626;
    }
  }
  .item:first-child{padding-left:0}

  .item.total {
    background: linear-gradient(130deg, #30a1ff, rgba(66, 175, 255, 0.6));
    border-radius: 10px;
    width: 12.8125vw;

    .label {
      color: #fff;
    }

    .value {
      font-size: 20px;
      color: #fff;
    }
  }

  .arrow-icon {
    width: 16px;
    height: 16px;
  }
}

.search {
  width: 100%;
  margin-top: 24px;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  .block {
    width: auto;
    padding-left: 30px;
    padding-right: 30px;
  }

  .search-btn {
    padding-left: 15px;
  }

  .search-btn,
  .select {
    width: 20%;
  }
}

.c-page__bg {
  width: 100%;
  height: 100%;
  margin-top: 25px;
  padding-bottom: 24px;
  flex-direction: column;
  background-color: #fff;
  border-radius: 10px;
  overflow: hidden;
}

.c-text-primary {
  font-size: 14px;
  color: #1c9fff;
  white-space: nowrap;
  cursor: pointer;
  padding-left: 5px;
  padding-right: 5px;
}

.pagination-block {
  padding-top: 20px;
  padding-right: 10px;
  display: flex;
  justify-content: flex-end;
}

.c-dot-success,
.c-dot-info {
  width: 6px;
  height: 6px;
  margin-right: 6px;
  display: inline-block;
  border-radius: 50%;
  flex-shrink: 0;
  background-color: #43bf0a;
}

.c-dot-info {
  background-color: #bfbfbf;
}

.system-icon-content {
  min-height: 500px;
}

.flex-row {
  margin-bottom: 16px;
  display: flex;
  justify-content: center;
  font-size: 16px;
  color: #262626;
}

.back {
  display: flex;
  align-items: center;
  font-size: 18px;
  color: #1c9fff;

  .back-text {
    display: flex;
    align-items: center;
    padding-right: 5px;
    font-size: 16px;
    cursor: pointer;
  }

  .title {
    color: #8c8c8c;
    font-size: 16px;
  }
}
</style>
